// 登录路由
import login from '@/views/login.ejs';
import axios from '@/api/index.js';
export default function (router) {
    router.route("/login", (req, res) => {
        res.render(login())

         // 一、校验用户名是否正确  ；
         let usernameEle = document.querySelector(".username");
         let exchangeEle = document.querySelector(".exchange");
         exchangeEle.innerHTML = "";
         usernameEle.onblur = async function () {
             // 失去焦点校验用户名是否正确；
             let username = this.value;
             if (username !== "") {
                 let { data :{status,info} } = await axios.get("/login/checkname", { params: { username } })
                 // console.log(data);
                 if(status===1){
                     exchangeEle.innerHTML = info;
                     exchangeEle.style.color = "green";
                 }else if(status===2){
                     exchangeEle.innerHTML = info;
                     exchangeEle.style.color = "red";
                 }else{
                     alert(info);
                 }
             } else {
                 alert("用户名不能为空");
             }
         }

          // 获取form表单
        let formEle = document.querySelector("form");
        formEle.onsubmit = function (e) {
            e.preventDefault();
        }

         // 校验密码
         let loginStyle = document.querySelector(".loginStyle");
         let pwdEle = document.querySelector(".pwd");
         loginStyle.onclick = async function(){
            let username = usernameEle.value;
            let pwd = pwdEle.value;

            let { data :{status,info,token} } = await axios.post("/login/checkuser", {username,pwd})
            if(status===1){
                // console.log("用户名且密码正确");
                localStorage.setItem("token",token);
                localStorage.setItem("username",username);
                window.location.href = "/admin/users";
            }else{
                alert(info);
            }
         }

    })
}